<?php
namespace app\jobmanagement\service;

use think\Db;
use think\Model;

use app\model\TaskWork as TaskWorkModel;
use app\model\TaskTask as TaskTaskModel;
use app\model\Settle as SettleModel;
use app\model\Product as ProductModel;
use app\model\ProductWork as ProductWorkModel;
use app\model\User as UserModel;
use app\model\ProductLadder as ProductLadderModel;
use app\model\ProductLadderItem as ProductLadderItemModel;

use app\lib\Dingtalk as DingtalkLib;

use app\jobmanagement\service\Common as CommonService;

class Task extends Model
{
    public $dd_user_id;

    public $mTask;

    public $mTaskWork;

    public $mSettle;

    public $task_status;

    public $is_sys;

    public $dept_id;

    public function __construct($data = [])
    {
        parent::__construct($data);
        $this->dd_user_id = session('dd_user_id');
        $this->mTask = new TaskTaskModel();
        $this->mTaskWork = new TaskWorkModel();
        $this->mSettle = new SettleModel();
        $this->task_status = config('dic.task_status');
        $this->is_sys = session('is_sys');
        $this->dept_id = session('dept_id');
    }

    /**
     * @description 获取不同类型的相关参数
     * @param $type 参数类型
     * @return array|array[]
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getTaskListParam($type)
    {
        $task_status = $this->task_status;
        $task_status_box = [];
        foreach ($task_status as $key => $val) {
            $task_status_box[] = ['status_id' => $key, 'status_name' => $val];
        }
        // 区分部门
        $add_where = [];
        if (!$this->is_sys && $this->dept_id) {
            $add_where['dept_id'] = $this->dept_id;
        }
        switch ($type) {
            case 1:
                // 待审核任务单
                $status = [1, 3, 5];
                $user = $this->mTask
                    ->where(['task_status' => ['in', $status]])
                    ->field('create_user')
                    ->group('create_user')
                    ->where($add_where)
                    ->select();
                $user_box = [];
                foreach ($user as $one) {
                    $user_box[] = ['user_id' => $one['create_user'], 'user_name' => get_user_name($one['create_user'])];
                }
                $status_check = [
                    ['status_id' => 1, 'status_name' => $task_status[1]],
                    ['status_id' => 3, 'status_name' => $task_status[3]],
                    ['status_id' => 5, 'status_name' => $task_status[5]],
                ];
                return ['user' => $user_box, 'status' => $status_check];
                break;
            case 2:
                // 所有任务单
                $user = $this->mTask
                    ->field('create_user')
                    ->group('create_user')
                    ->where($add_where)
                    ->select();
                $user_box = [];
                foreach ($user as $one) {
                    $user_box[] = ['user_id' => $one['create_user'], 'user_name' => get_user_name($one['create_user'])];
                }
                return ['user' => $user_box, 'status' => $task_status_box];
                break;
            case 3:
                // 我提交的任务单
                return ['user' => [], 'status' => $task_status_box];
                break;
            case 4:
                // 我相关的任务单
                // 工种中有我参与的任务单
                $task_ids = $this->mTaskWork
                    ->where(['worker' => ['like', '%-'.$this->dd_user_id.'-%']])
                    ->group('task_id')
                    ->field('task_id')
                    ->select();
                $task_ids_array = [];
                foreach ($task_ids as $one) {
                    $task_ids_array[] = $one['task_id'];
                }
                if (empty($task_ids_array)) {
                    $user_box = [];
                } else {
                    $user = $this->mTask
                        ->where(['id' => ['in', $task_ids_array]])
                        ->field('create_user')
                        ->group('create_user')
                        ->select();
                    foreach ($user as $one) {
                        $user_box[] = ['user_id' => $one['create_user'], 'user_name' => get_user_name($one['create_user'])];
                    }
                }
                return ['user' => $user_box, 'status' => $task_status_box];
                break;
            default:
                return ['user' => [], 'status' => []];
        }
    }

    /**
     * @auther zlq
     * @description 获取不同类型和相关参数查询任务单列表
     * @param $type 类型
     * @param $param 查询参数
     * @return array|bool|false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getTaskListByType($type, $param)
    {
        // 处理筛选参数
        $task_status = $this->task_status;
        $select = [];
        if (isset($param['status']) && $param['status']) {
            $select['task_status'] = $param['status'];
        }
        if (isset($param['user']) && $param['user']) {
            $select['create_user'] = $param['user'];
        }
        if (isset($param['date']) && $param['date']) {
            $select['task_date'] = $param['date'];
        }
        $param['page'] = $param['page'] > 1 ? $param['page'] : 1;
        $page_size = PAGE_SIZE;
        $offset = ($param['page'] - 1) * $page_size;
        // 区分部门
        $add_where = [];
        if (!$this->is_sys && $this->dept_id) {
            $add_where['dept_id'] = $this->dept_id;
        }
        switch ($type) {
            case 1:
                // 待审核任务单
                if (!isset($select['task_status'])) {
                    $select['task_status'] = ['in', [1, 3, 5]];
                }
                $task_list = $this->mTask
                    ->where($select)
                    ->limit($offset, $page_size)
                    ->where($add_where)
                    ->order('id desc')
                    ->select();
                break;
            case 2:
                // 所有任务单
                $task_list = $this->mTask
                    ->where($select)
                    ->limit($offset, $page_size)
                    ->where($add_where)
                    ->order('id desc')
                    ->select();
                break;
            case 3:
                // 我提交的任务单
                $select['create_user'] = $this->dd_user_id;
                $task_list = $this->mTask
                    ->where($select)
                    ->limit($offset, $page_size)
                    ->order('id desc')
                    ->select();
                break;
            case 4:
                // 我相关的任务单
                // 工种中有我参与的任务单
                $task_ids = $this->mTaskWork
                    ->where(['worker' => ['like', '%-'.$this->dd_user_id.'-%']])
                    ->group('task_id')
                    ->field('task_id')
                    ->select();
                $task_ids_array = [];
                foreach ($task_ids as $one) {
                    $task_ids_array[] = $one['task_id'];
                }
                if (empty($task_ids_array)) {
                    return [];
                } else {
                    $task_list = $this->mTask
                        ->where($select)
                        ->where(['id' => ['in', $task_ids_array]])
                        ->limit($offset, $page_size)
                        ->order('id desc')
                        ->select();
                }
                break;
            default:
                return [];
        }
        // 处理任务单相关显示
        if (empty($task_list)) {
            return [];
        } else {
            $box = [];
            foreach ($task_list as $key => $item) {
                $temp = $item->toArray();
                $temp['task_status_name'] = $task_status[$item['task_status']];
                $temp['create_user'] = get_user_name($item['create_user']);
                $temp['prod_number'] = floatval($temp['prod_number']);
                $box[] = $temp;
            }
            return $box;
        }
    }

    /**
     * @auther zlq
     * @description 获取不同类型和相关参数查询任务单列表
     * @param int $task_id 任务单ID
     * @return array|bool|false|\PDOStatement|string|Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getTaskInfo($task_id = 0) {
        if (!$task_id) {
            return [];
        }
        $task = $this->mTask
            ->where(['id' => $task_id])
            ->find();
        if (empty($task)) {
            return [];
        }
        $task = $task->toArray();
        $task_status = $this->task_status;
        $task['task_status_name'] = $task_status[$task['task_status']];
        $task['create_user'] = get_user_name($task['create_user']);
        $task['prod_number'] = floatval($task['prod_number']);
        $task_work = $this->mTaskWork
            ->where(['task_id' => $task_id])
            ->select();
        if (empty($task_work)) {
            return [];
        }
        // 处理相关信息
        $work_list = [];
        foreach ($task_work as $one) {
            $temp = [
                'work_id' => $one['id'],
                'name' => $one['name'],
                'proportion' => $one['proportion'],
                'amount' => $one['amount'],
                'worker_amount' => $one['worker_amount'],
            ];
            $worker = explode('-', trim($one['worker'], '-'));
            if (empty($worker)) {
                $temp['worker'] = [];
            } else {
                foreach ($worker as $item) {
                    $temp['worker'][] = [
                        'worker_id' => $item,
                        'worker_name' => get_user_name($item),
                        'is_select' => $this->dd_user_id == $item ? 1 : 0
                    ];
                }
            }
            $work_list[] = $temp;
        }
        $task['work'] = $work_list;
        return $task;
    }

    /**
     * @auther zlq
     * @create_time 2020/5/19 14:19
     * @description 审核通过任务单
     * @param int $task_id 任务单id
     * @param string $remark 备注
     * @param string $number 修改产品数量
     * @return array|int
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function taskAuditCheckPass($task_id = 0, $remark = '', $number = 0)
    {
        if (!$task_id) {
            return -1;
        }
        $task = $this->mTask
            ->where(['id' => $task_id])
            ->find();
        if (empty($task)) {
            return -2;
        }
        $time = date('Y-m-d H:i:s');
        $user_name = get_user_name($this->dd_user_id);
        $DingTalkService = new DingtalkLib();
        $mProd = new ProductModel();
        switch ($task['task_status']) {
            case 1:
                // 待确认审核
                if ($remark) {
                    $tip = $user_name . '于' . $time .'审核通过确认任务单,备注:' . $remark . ';';
                } else {
                    $tip = $user_name . '于' . $time .'审核通过确认任务单;';
                }
                $update = [
                    'task_status' => 2,
                    'status_remark' => $task['status_remark'] . $tip
                ];
                $res = $this->mTask
                    ->where(['id' => $task_id])
                    ->update($update);
                addLog($tip, 1, $task_id, $user_name);
                $DingTalkService->sendNoticeMessage($task['create_user'], $tip);
                break;
            case 3:
                // 待生产审核
                // 判断任务单数量是否被修改
                $prod = $mProd
                    ->where(['id' => $task['prod_id']])
                    ->find();
                if (empty($prod)) {
                    return -3;
                }
                // 验证商品数量 根据单位判断参数，万件可以为小数
                $origin_number = $number;
                $temp_prod_num = floatval($task['prod_number']);
                $number = floatval($number);
                if ($origin_number > 0 && $temp_prod_num != $number) {
                    if ($prod['unit'] < 10) {
                        $number = (int)$number;
                        if ($number < 1) {
                            return -4;
                        }
                    } else {
                        $number_ex = (string)$number;
                        $temp_num = explode('.', $number_ex);
                        if (isset($temp_num[1]) && (strlen($temp_num[1]) > 4)) {
                            return -5;
                        }
                    }
                    $task_work = $this->mTaskWork
                        ->where(['task_id' => $task_id])
                        ->select();
                    // 重新计算任务单和子任务单金额
                    if ($task['task_type']  == 1) {
                        $new_task_amount = $number * $task['prod_amount'] * $task['task_worker_amount'];
                    } else {
                        $new_task_amount = $number * $task['prod_amount'];
                    }
                    $task_work_update_box = [];
                    foreach ($task_work as $one) {
                        $worker = explode('-', trim($one['worker'], '-'));
                        if (empty($worker)) {
                            return -6;
                        } else {
                            // 计算产品数量变化引起的价格变化
                            if ($task['task_type']  == 1) {
                                $one_amount = $new_task_amount * $one['worker_number'] / $task['task_worker_amount'];
                            } else {
                                $one_amount = $new_task_amount * $one['proportion'] / 100;
                            }
                            $one_amount_save = sprintf("%.2f", $one_amount);
                            $one_worker_amount = $one_amount / $one['worker_number'];
                            $one_worker_amount =  sprintf("%.2f", $one_worker_amount);
                            $task_work_update_box[] = [
                                'id' => $one['id'],
                                'amount' => $one_amount_save,
                                'worker_amount' => $one_worker_amount
                            ];
                        }
                    }
                    // 处理任务单审批数据
                    if ($remark) {
                        $tip = $user_name . '于' . $time .'审核通过结算任务单,备注:' . $remark . ',';
                    } else {
                        $tip = $user_name . '于' . $time .'审核通过结算任务单,';
                    }
                    $tip .= "并将产品数量由". $temp_prod_num ."修改为".$number.";";
                    $update = [
                        'task_amount' => $new_task_amount,
                        'prod_number' => $number,
                        'task_status' => 4,
                        'status_remark' => $task['status_remark'] . $tip
                    ];
                    try {
                        Db::startTrans();
                        $res1 = $this->mTask
                            ->where(['id' => $task_id])
                            ->update($update);
                        $res2 = $this->mTaskWork->isUpdate(true)->saveAll($task_work_update_box);
                        if ($res1 && $res2) {
                            $res = 1;
                            Db::commit();
                            addLog($tip, 1, $task_id, $user_name);
                            $DingTalkService->sendNoticeMessage($task['create_user'], $tip);
                        } else {
                            $res = 0;
                            Db::rollback();
                        }
                    } catch (\Exception $exception) {
                        $res = 0;
                        Db::rollback();
                        addLog($exception->getMessage());
                    }
                } else {
                    if ($remark) {
                        $tip = $user_name . '于' . $time . '审核通过生产任务单,备注:' . $remark . ';';
                    } else {
                        $tip = $user_name . '于' . $time . '审核通过生产任务单;';
                    }
                    $update = [
                        'task_status' => 4,
                        'status_remark' => $task['status_remark'] . $tip
                    ];
                    $res = $this->mTask
                        ->where(['id' => $task_id])
                        ->update($update);
                    addLog($tip, 1, $task_id, $user_name);
                    $DingTalkService->sendNoticeMessage($task['create_user'], $tip);
                }
                break;
            case 5:
                // 待提现审核
                // 组成结算单数据
                $settle_box = [];
                $task_work = $this->mTaskWork
                    ->where(['task_id' => $task_id])
                    ->select();
                if (empty($task_work)) {
                    return [];
                }
                // 处理相关信息
                $code = 'D'.$task['id'];
                $code_length = 12 - strlen($code);
                $range = 1;
                // 进行审核时修改了产品数量
                $prod = $mProd
                    ->where(['id' => $task['prod_id']])
                    ->find();
                if (empty($prod)) {
                    return -3;
                }
                // 验证商品数量 根据单位判断参数，万件可以为小数
                $origin_number = $number;
                $temp_prod_num = floatval($task['prod_number']);
                $number = floatval($number);
                if ($origin_number > 0 && $temp_prod_num != $number) {
                    if ($prod['unit'] < 10) {
                        $number = (int)$number;
                        if ($number < 1) {
                            return -4;
                        }
                    } else {
                        $number_ex = (string)$number;
                        $temp_num = explode('.', $number_ex);
                        if (isset($temp_num[1]) && (strlen($temp_num[1]) > 4)) {
                            return -5;
                        }
                    }
                    // 重新计算任务单和子任务单金额
                    if ($task['task_type']  == 1) {
                        $new_task_amount = $number * $task['prod_amount'] * $task['task_worker_amount'];
                    } else {
                        $new_task_amount = $number * $task['prod_amount'];
                    }
                    $task_work_update_box = [];
                    foreach ($task_work as $one) {
                        $worker = explode('-', trim($one['worker'], '-'));
                        if (empty($worker)) {
                            return -6;
                        } else {
                            // 计算产品数量变化引起的价格变化
                            if ($task['task_type']  == 1) {
                                $one_amount = $new_task_amount * $one['worker_number'] / $task['task_worker_amount'];
                            } else {
                                $one_amount = $new_task_amount * $one['proportion'] / 100;
                            }
                            $one_amount_save = sprintf("%.2f", $one_amount);
                            $one_worker_amount = $one_amount / $one['worker_number'];
                            $one_worker_amount =  sprintf("%.2f", $one_worker_amount);
                            $task_work_update_box[] = [
                                'id' => $one['id'],
                                'amount' => $one_amount_save,
                                'worker_amount' => $one_worker_amount
                            ];
                            foreach ($worker as  $item) {
                                $temp = str_pad($range, $code_length, '0');
                                $settle_box[] = [
                                    'settle_code' => $code . $temp,
                                    'task_id' => $task['id'],
                                    'work_id' => $one['id'],
                                    'amount' => $one_worker_amount,
                                    //'settle_status' => 1,
                                    'settle_status' => 2,
                                    'leader' => $one['create_user'],
                                    'create_time' => $time,
                                    'create_user' => $item,
                                    'dept_id' => $task['dept_id'],
                                ];
                                $range++;
                            }
                        }
                    }
                    if (empty($settle_box)) {
                        return -7;
                    }
                    // 处理任务单审批数据
                    if ($remark) {
                        $tip = $user_name . '于' . $time .'审核通过结算任务单,备注:' . $remark . ';';
                    } else {
                        $tip = $user_name . '于' . $time .'审核通过结算任务单;';
                    }
                    $tip .= '并将产品数量由' . $temp_prod_num . '改为' . $number;
                    $update = [
                        'task_amount' => $new_task_amount,
                        'prod_number' => $number,
                        'task_status' => 6,
                        'status_remark' => $task['status_remark'] . $tip
                    ];
                    try {
                        Db::startTrans();
                        $res1 = $this->mTask
                            ->where(['id' => $task_id])
                            ->update($update);
                        $res2 = $this->mSettle
                            ->insertAll($settle_box);
                        $res3 = $this->mTaskWork->isUpdate(true)->saveAll($task_work_update_box);
                        if ($res1 && $res2 && $res3) {
                            $res = 1;
                            $DingTalkService->sendNoticeMessage($task['create_user'], $tip);
                            addLog($tip, 1, $task_id, $user_name);
                            Db::commit();
                        } else {
                            $res = 0;
                            Db::rollback();
                        }
                    } catch (\Exception $exception) {
                        $res = 0;
                        Db::rollback();
                        dump($exception->getMessage());
                    }
                } else {
                    foreach ($task_work as $one) {
                        $worker = explode('-', trim( $one['worker'], '-'));
                        if (empty($worker)) {
                            return -6;
                        } else {
                            foreach ($worker as  $item) {
                                $temp = str_pad($range, $code_length, '0');
                                $settle_box[] = [
                                    'settle_code' => $code . $temp,
                                    'task_id' => $task['id'],
                                    'work_id' => $one['id'],
                                    'amount' => $one['worker_amount'],
                                    'settle_status' => 2,
                                    'leader' => $one['create_user'],
                                    'create_time' => $time,
                                    'create_user' => $item,
                                    'dept_id' => $task['dept_id'],
                                ];
                                $range++;
                            }
                        }
                    }
                    if (empty($settle_box)) {
                        return -7;
                    }
                    // 处理任务单审批数据
                    if ($remark) {
                        $tip = $user_name . '于' . $time .'审核通过结算任务单,备注:' . $remark . ',';
                    } else {
                        $tip = $user_name . '于' . $time .'审核通过结算任务单,';
                    }
                    $tip .= "并将产品数量由" . $task['prod_number'] . "改为" . $number . ";";
                    $update = [
                        'task_status' => 6,
                        'status_remark' => $task['status_remark'] . $tip
                    ];
                    try {
                        Db::startTrans();
                        $res1 = $this->mTask
                            ->where(['id' => $task_id])
                            ->update($update);
                        $res2 = $this->mSettle
                            ->insertAll($settle_box);
                        if ($res1 && $res2) {
                            $res = 1;
                            $DingTalkService->sendNoticeMessage($task['create_user'], $tip);
                            addLog($tip, 1, $task_id, $user_name);
                            Db::commit();
                        } else {
                            $res = 0;
                            Db::rollback();
                        }
                    } catch (\Exception $exception) {
                        $res = 0;
                        Db::rollback();
                    }
                }
                break;
            default:
                return 0;
        }
        return $res;
    }

    /**
     * @auther zlq
     * @create_time 2020/5/19 14:03
     * @description 审批退回任务单
     * @param int $task_id 任务单ID
     * @param string $remark 备注
     * @return array|int
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function taskAuditCheckRefuse($task_id = 0, $remark = '')
    {
        if (!$task_id) {
            return 0;
        }
        $task = $this->mTask
            ->where(['id' => $task_id])
            ->find();
        if (empty($task)) {
            return 0;
        }
        $time = date('Y-m-d H:i:s');
        $user_name = get_user_name($this->dd_user_id);
        $DingTalkService = new DingtalkLib();
        switch ($task['task_status']) {
            case 1:
                // 待确认审核
                if ($remark) {
                    $tip = $user_name . '于' . $time . '审核退回确认任务单,备注:' . $remark . ';';
                } else {
                    $tip = $user_name . '于' . $time . '审核退回确认任务单;';
                }
                $update = [
                    'task_status' => 99,
                    'status_remark' => $task['status_remark'] . $tip
                ];
                $res = $this->mTask
                    ->where(['id' => $task_id])
                    ->update($update);
                $DingTalkService->sendNoticeMessage($task['create_user'], $tip);
                break;
            case 3:
                // 待生产审核
                if ($remark) {
                    $tip = $user_name . '于' . $time . '审核退回生产任务单,备注:' . $remark . ';';
                } else {
                    $tip = $user_name . '于' . $time . '审核退回生产任务单;';
                }
                $update = [
                    'task_status' => 2,
                    'status_remark' => $task['status_remark'] . $tip
                ];
                $res = $this->mTask
                    ->where(['id' => $task_id])
                    ->update($update);
                $DingTalkService->sendNoticeMessage($task['create_user'], $tip);
                break;
            case 5:
                // 待提现审核
                if ($remark) {
                    $tip = $user_name . '于' . $time . '审核退回结算任务单,备注:' . $remark . ';';
                } else {
                    $tip = $user_name . '于' . $time . '审核退回结算任务单;';
                }
                $update = [
                    'task_status' => 4,
                    'status_remark' => $task['status_remark'] . $tip
                ];
                $res = $this->mTask
                    ->where(['id' => $task_id])
                    ->update($update);
                $DingTalkService->sendNoticeMessage($task['create_user'], $tip);
                break;
            default:
                return 0;
        }
        if ($res) {
            return 1;
        } else {
            return 0;
        }
    }

    /**
     * @auther zlq
     * @create_time 2020/5/19 14:41
     * @description 确认任务单产品生产完毕
     * @param int $task_id 任务单ID
     * @return int
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function taskConfirmProduce($task_id = 0)
    {
        if (!$task_id) {
            return -1;
        }
        $task = $this->mTask
            ->where(['id' => $task_id])
            ->find();
        if (empty($task)) {
            return -2;
        }
        if ($task['task_status'] != 2) {
            return -3;
        }
        $tip = get_user_name($this->dd_user_id) . '于' . date('Y-m-d H:i:s') . '申请确认生成任务单;';
        $update = [
            'task_status' => 3,
            'status_remark' => $task['status_remark'] . $tip
        ];
        $res = $this->mTask
            ->where(['id' => $task_id])
            ->update($update);
        if ($res) {
            return 1;
        } else {
            return 0;
        }
    }

    /**
     * @auther zlq
     * @create_time 2020/5/19 14:42
     * @description 申请提现任务单
     * @param int $task_id 任务单ID
     * @return int
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function settleTask($task_id = 0)
    {
        if (!$task_id) {
            return -1;
        }
        $task = $this->mTask
            ->where(['id' => $task_id])
            ->find();
        if (empty($task)) {
            return -2;
        }
        if ($task['task_status'] != 4) {
            return -3;
        }
        $tip = get_user_name($this->dd_user_id) . '于' . date('Y-m-d H:i:s') . '申请确认结算任务单;';
        $update = [
            'task_status' => 5,
            'status_remark' => $task['status_remark'] . $tip
        ];
        $res = $this->mTask
            ->where(['id' => $task_id])
            ->update($update);
        if ($res) {
            return 1;
        } else {
            return 0;
        }
    }

    /**
     * @auther zlq
     * @create_time 2020/5/19 18:57
     * @description 保存任务单数据
     * @param $param 相关参数
     * @return int
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function taskSave($param)
    {
        $now_user = session('dd_user_id');
        $now_user_name = get_user_name($now_user);
        $now_time = date('Y-m-d H:i:s');
        $prod_unit = config('dic.prod_unit');
        $mProdWork = new ProductWorkModel();
        $mUser = new UserModel();
        $DingTalkService = new DingtalkLib();
        $sCommon = new CommonService();
        $mProd = new ProductModel();

        $new_task = [];
        // 匹配日期格式
        if (preg_match ("/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/", $param['task_date'], $parts)) {
            if(!checkdate($parts[2],$parts[3],$parts[1])) {
                return -2;
            }
        } else {
            return -2;
        }
        $new_task['task_date'] = $param['task_date'];
        // 验证商品信息 产品是否存在
        $prod = $mProd
            ->where(['id' => $param['prod_id']])
            ->find();
        if (empty($prod)) {
            return -3;
        }

        // 验证商品数量 根据单位判断参数，万件可以为小数
        $prod_num = floatval($param['number']);
        if ($prod['unit'] < 10) {
            $prod_num = (int)$prod_num;
            if ($prod_num < 1) {
                return -1;
            }
        } else {
            $prod_num_ex = (string)$prod_num;
            $temp_num = explode('.', $prod_num_ex);
            if (isset($temp_num[1]) && (strlen($temp_num[1]) > 4)) {
                return -20;
            }
        }
        $new_task['dept_id'] = $prod['dept_id'];
        $new_task['prod_number'] = $prod_num;
        $new_code = $sCommon->getNewTaskCode();
        $new_task['task_type'] = $param['type'];
        $new_task['prod_id'] = $param['prod_id'];
        $new_task['prod_name'] = $prod['name'];
        $new_task['task_code'] = $new_code;
        $new_task['prod_amount'] = $prod['amount'];
        $new_task['prod_unit'] = $prod_unit[$prod['unit']];
        $new_task['create_time'] = $now_time;
        $new_task['create_user'] = $now_user;
        $new_task['remark'] = $param['remark'];
        $new_task['task_status'] = 1;
        $new_task['status_remark'] = $now_user_name . '于' . $now_time . '提交了任务单';
        $task_worker_number = 0;
        // 后期提取公共模式
        switch($param['type']) {
            case 1:
                // 按件计费
                try {
                    $new_user = [];
                    $new_prod_box = [];
                    $all_user_box = [];
                    Db::startTrans();
                    // 处理工种相关数据
                    $work = $param['work'];
                    // 验证工种信息
                    foreach ($work as $key => $value) {
                        if (!($value['prod_work_id'] && $value['worker'])) {
                            return -10;
                        }
                        // 校验工种信息是否正确 是否与产品匹配
                        $work = $mProdWork->where(['id' => $value['prod_work_id']])->find();
                        if (empty($work)) {
                            return -13;
                        }
                        if ($work['prod_id'] != $param['prod_id']) {
                            return -14;
                        }
                        // 验证工人相关信息
                        $worker = explode(',', trim($value['worker'], ','));
                        if (empty($worker)) {
                            return -17;
                        }
                        foreach ($worker as $one) {
                            // 判断该用户是否在我们系统数据库中，如果有则跳过，如果没有则查询钉钉添加
                            if (in_array($one, $all_user_box)) {
                                return -15;
                            }
                            $all_user_box[] = $one;
                            $user_info = $mUser->where(['dd_user_id' => $one])->find();
                            // 本地数据查询不到，到钉钉中查询然后添加到本地中
                            if (empty($user_info)) {
                                $user_dd_info = $DingTalkService->getUserInfoByDDUserId($one);
                                // 查询不到该该用户
                                if (empty($user_dd_info)) {
                                    return -16;
                                } else {
                                    $new_user[] = [
                                        'dd_user_id' => $one,
                                        'name' => $user_dd_info['name'],
                                        'avatar' => $user_dd_info['avatar'],
                                        'level' => 1,
                                    ];
                                }
                            }
                            $task_worker_number++;
                        }
                        // 处理工种对应比例，总金额，总人数，人均金额，人员钉钉ID
                        $one_worker_number = count($worker);
                        $one_amount = $prod['amount'] * $prod_num * $one_worker_number;
                        $one_amount_save = sprintf("%.2f", $one_amount);
                        $one_worker_amount = $one_amount / $one_worker_number;
                        $one_worker_amount =  sprintf("%.2f", $one_worker_amount);
                        $one_worker = implode('-', $worker);
                        $one_worker = '-' . $one_worker . '-';
                        $new_prod_box[] = [
                            'task_id' => 0,
                            'name' => $work['name'],
                            'proportion' => 0,
                            'amount' => $one_amount_save,
                            'worker' => $one_worker,
                            'worker_number' => $one_worker_number,
                            'worker_amount' => $one_worker_amount,
                            'create_time' => $now_time,
                            'create_user' => $now_user,
                        ];
                    }
                    // 计算任务单总金额
                    $task_amount = $prod['amount'] * $prod_num * $task_worker_number;
                    $new_task['task_amount'] = sprintf('%.2f', $task_amount);
                    // 修改工种对应比率
                    if (empty($new_prod_box)) {
                        return -10;
                    }
                    // 保存新任务单
                    $new_task['task_worker_amount'] = $task_worker_number;
                    $res_task = $this->mTask->insertGetId($new_task);
                    // 再次处理产品信息
                    foreach ($new_prod_box as $em => $foo) {
                        $new_prod_box[$em]['task_id'] = $res_task;
                        $new_prod_box[$em]['proportion'] = sprintf('%.2f', $foo['worker_number'] / $task_worker_number) * 100;
                    }
                    // 保存工种和用户信息
                    $res_work = $this->mTaskWork->insertAll($new_prod_box);
                    // 判断是否有新工人，可能添加的都是老工人所以不需要添加
                    if (empty($new_user)) {
                        $res_user = true;
                    } else {
                        $res_user = $mUser->insertAll($new_user);
                    }
                    if ($res_task && $res_work && $res_user) {
                        Db::commit();
                        return 1;
                    } else {
                        Db::rollback();
                        return 0;
                    }
                } catch (\Exception $exception) {
                    Db::rollback();
                    addLog($exception->getMessage(), 1001, 0, $now_user_name);
                    return 0;
                }
                break;
            case 2:
                // 按照比率计费
                try {
                    // 计算任务单总金额
                    $task_amount = $prod['amount'] * $prod_num;
                    $new_task['task_amount'] = sprintf('%.2f', $task_amount);
                    $new_user = [];
                    $new_prod_box = [];
                    $all_user_box = [];
                    Db::startTrans();
                    // 处理工种相关数据
                    $work = $param['work'];
                    // 验证工种信息
                    $proportion_all = 0;
                    foreach ($work as $key => $value) {
                        if (!($value['prod_work_id'] && $value['proportion'] && $value['worker'])) {
                            return -10;
                        }
                        // 验证比例信息 - 比例填写不正确
                        $value['proportion'] = (int)$value['proportion'];
                        if ($value['proportion'] < 1 || $value['proportion'] > 100) {
                            return -11;
                        }
                        // 验证比例信息 - 比例总值超过100
                        $proportion_all += $value['proportion'];
                        if ($proportion_all > 100) {
                            return -12;
                        }
                        // 校验工种信息是否正确 是否与产品匹配
                        $work = $mProdWork->where(['id' => $value['prod_work_id']])->find();
                        if (empty($work)) {
                            return -13;
                        }
                        if ($work['prod_id'] != $param['prod_id']) {
                            return -14;
                        }
                        // 验证工人相关信息
                        $worker = explode(',', trim($value['worker'], ','));
                        if (empty($worker)) {
                            return -17;
                        }
                        foreach ($worker as $one) {
                            // 判断该用户是否在我们系统数据库中，如果有则跳过，如果没有则查询钉钉添加
                            if (in_array($one, $all_user_box)) {
                                return -15;
                            }
                            $all_user_box[] = $one;
                            $user_info = $mUser->where(['dd_user_id' => $one])->find();
                            // 本地数据查询不到，到钉钉中查询然后添加到本地中
                            if (empty($user_info)) {
                                $user_dd_info = $DingTalkService->getUserInfoByDDUserId($one);
                                // 查询不到该该用户
                                if (empty($user_dd_info)) {
                                    return -16;
                                } else {
                                    $new_user[] = [
                                        'dd_user_id' => $one,
                                        'name' => $user_dd_info['name'],
                                        'avatar' => $user_dd_info['avatar'],
                                        'level' => 3,
                                        'dept_id' => 0,
                                    ];
                                }
                            }
                            $task_worker_number++;
                        }
                        // 处理工种对应比例，总金额，总人数，人均金额，人员钉钉ID
                        $one_amount = $task_amount * $value['proportion'] / 100;
                        $one_amount_save = sprintf("%.2f", $one_amount);
                        $one_worker_number = count($worker);
                        $one_worker_amount = $one_amount / $one_worker_number;
                        $one_worker_amount =  sprintf("%.2f", $one_worker_amount);
                        $one_worker = implode('-', $worker);
                        $one_worker = '-' . $one_worker . '-';
                        $new_prod_box[] = [
                            'task_id' => 0,
                            'name' => $work['name'],
                            'proportion' => $value['proportion'],
                            'amount' => $one_amount_save,
                            'worker' => $one_worker,
                            'worker_number' => $one_worker_number,
                            'worker_amount' => $one_worker_amount,
                            'create_time' => $now_time,
                            'create_user' => $now_user,
                        ];
                    }
                    if ($proportion_all != 100) {
                        return -18;
                    }
                    // 保存新任务单
                    $new_task['task_worker_amount'] = $task_worker_number;
                    $res_task = $this->mTask->insertGetId($new_task);
                    // 再次处理产品信息
                    foreach ($new_prod_box as $em => $foo) {
                        $new_prod_box[$em]['task_id'] = $res_task;
                    }
                    // 保存工种和用户信息
                    $res_work = $this->mTaskWork->insertAll($new_prod_box);
                    // 判断是否有新工人，可能添加的都是老工人所以不需要添加
                    if (empty($new_user)) {
                        $res_user = true;
                    } else {
                        $res_user = $mUser->insertAll($new_user);
                    }
                    if ($res_task && $res_work && $res_user) {
                        addLog($new_task['status_remark'], 1, $res_task, $now_user_name);
                        Db::commit();
                        return 1;
                    } else {
                        Db::rollback();
                        return 0;
                    }
                } catch (\Exception $exception) {
                    Db::rollback();
                    return 0;
                }
                break;
            case 3:
                try {
                    $new_user = [];
                    $new_prod_box = [];
                    $total_price = 0;
                    $total_num = 0;
                    // 验证产品对应阶级能否使用
                    if (!$param['ladder']) {
                        return -21;
                    }
                    $ladder_list = $param['ladder_list'];
                    if (empty($ladder_list)) {
                        return -21;
                    }
                    $productLadderModel = new ProductLadderModel();
                    $productLadderItemModel = new ProductLadderItemModel();
                    $ladder = $productLadderModel->where(['id' => $param['ladder']])->find();
                    // 查询是否有对应的阶梯价格
                    if (empty($ladder)) {
                        return -22;
                    }
                    // 查询产品阶梯价格
                    if ($ladder['status'] != 1) {
                        return -23;
                    }
                    $ladder_item = $productLadderItemModel
                        ->where(['ladder_id' => $param['ladder']])
                        ->order('num_min asc')
                        ->select();
                    $last_ladder_item = end($ladder_item);
                    $max_num = $last_ladder_item['num_max'];
                    if (empty($ladder_item)) {
                        return -22;
                    }
                    // 处理阶梯相关数据
                    foreach ($ladder_list as $roo => $foo) {
                        if ((!isset($foo['user_id'])) && !isset($foo['num'])) {
                            return -25;
                        }
                        $temp_num = (int)$foo['num'];
                        // 数量不正确
                        if ($temp_num < 1) {
                            return -26;
                        }
                        // 数量超过阶梯最大值
                        if ($temp_num > $max_num) {
                            return -27;
                        }
                        // 处理用户信息
                        $user_info = $mUser->where(['dd_user_id' => $foo['user_id']])->find();
                        // 本地数据查询不到，到钉钉中查询然后添加到本地中
                        if (empty($user_info)) {
                            $user_dd_info = $DingTalkService->getUserInfoByDDUserId($foo['user_id']);
                            // 查询不到该该用户
                            if (empty($user_dd_info)) {
                                return -16;
                            } else {
                                $new_user[] = [
                                    'dd_user_id' => $foo['user_id'],
                                    'name' => $user_dd_info['name'],
                                    'avatar' => $user_dd_info['avatar'],
                                    'level' => 1,
                                ];
                            }
                        }
                        $one_amount = 0;
                        foreach ($ladder_item as $key => $item) {
                            // 判断第一阶梯是否是从0开始的，不是的话需要计算初始值
                            if ($key == 0 && ($item['num_min']) > 0) {
                                // 判断产品数量是否超过第一阶梯最小值
                                if ($item['num_min'] >= $prod_num) {
                                    // 没达到
                                    $one_amount = $prod_num * $prod['amount'];
                                    // 也不用去计算阶梯了，直接退出
                                    break;
                                } else {
                                    // 达到了阶梯，那么金额就要分开计算了，1.计算未到达阶梯的部分，2.达到阶梯的那一部分
                                    $one_amount = $item['num_min'] * $prod['amount'];
                                }
                            }
                            // 产品数量超过阶梯的数量最小值, 小于等于阶梯最大值
                            if (($prod_num > $item['num_min']) && ($item['num_max'] >= $prod_num)) {
                                $one_amount += ($prod_num - $item['num_min']) * $item['price'];
                                break;
                            }
                            if (($prod_num > $item['num_min']) && ($item['num_max'] < $prod_num)) {
                                $one_amount += ($item['num_max'] - $item['num_min']) * $item['price'];
                                break;
                            }
                        }
                        // 计算之后价格还为0那肯定有问题
                        if ($one_amount <= 0) {
                            return -28;
                        }
                        $one_amount_save = sprintf("%.2f", $one_amount);
                        // 计算任务单总金额
                        $total_price += $one_amount_save;
                        // 计算总数量是否匹配
                        $total_num += $foo['num'];
                        // 组装工种数据
                        $new_prod_box[] = [
                            'task_id' => 0,
                            'name' => '生产',
                            'proportion' => 0,
                            'num' => $foo['num'],
                            'amount' => $one_amount_save,
                            'worker' => '-'.$foo['user_id'].'-',
                            'worker_number' => 1,
                            'worker_amount' => $one_amount_save,
                            'create_time' => $now_time,
                            'create_user' => $now_user,
                        ];
                    }
                    // 判断总数量和计算的数量是否一致
                    if ($new_task['prod_number'] !== $total_num) {
                        return -24;
                    }
                    // 保存新任务单
                    $new_task['task_worker_amount'] = $total_price;
                    $res_task = $this->mTask->insertGetId($new_task);
                    // 再次处理产品信息
                    foreach ($new_prod_box as $em => $foo) {
                        $new_prod_box[$em]['task_id'] = $res_task;
                        // 计算比例
                        $new_prod_box[$em]['proportion'] = sprintf('%.2f', $foo['amount'] / $total_price);
                    }
                    // 保存工种和用户信息
                    $res_work = $this->mTaskWork->insertAll($new_prod_box);
                    // 判断是否有新工人，可能添加的都是老工人所以不需要添加
                    if (empty($new_user)) {
                        $res_user = true;
                    } else {
                        $res_user = $mUser->insertAll($new_user);
                    }
                    if ($res_task && $res_work && $res_user) {
                        addLog($new_task['status_remark'], 1, $res_task, $now_user_name);
                        Db::commit();
                        return 1;
                    } else {
                        Db::rollback();
                        return 0;
                    }
                } catch (\Exception $exception) {
                    Db::rollback();
                    return 0;
                }
                break;
            default:
                return -19;
        }
    }
}